<template>
  <div class="account-box">
    <div class="toggle">
      <a href="javascript:;" v-if="type === 'account'" @click="type = 'mobile'">
        <i class="iconfont icon-user"></i> 使用账号登录
      </a>
      <a href="javascript:;" v-else @click="type = 'account'">
        <i class="iconfont icon-msg"></i> 使用短信登录
      </a>
    </div>
    <div class="form">
      <template v-if="type === 'account'">
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <input
            v-model="account" type="text" placeholder="请输入用户名" />
          </div>
          <div class="error" v-if="accountError">
              <i class="iconfont icon-warning" />{{ accountError }}
            </div>
          <!-- 表单验证错误信息提示 -->
          <!-- <div class="error"><i class="iconfont icon-warning" />请输入手机号</div> -->
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-lock"></i>
            <input
            v-model="password" type="password" placeholder="请输入密码" />
          </div>
          <div class="error" v-if="passwordError">
              <i class="iconfont icon-warning" />{{ passwordError }}
            </div>
        </div>
      </template>
      <template v-else>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <input
              v-model="mobile"
              type="text"
              placeholder="请输入手机号"
              ref="mobileRef"
            />
          </div>
          <div class="error" v-if="mobileError">
              <i class="iconfont icon-warning" />{{ mobileError }}
            </div>
          <!-- <div class="error"><i class="iconfont icon-warning" />请输入手机号</div> -->
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-code"></i>
            <input type="password"  v-model="code" placeholder="请输入验证码" />
            <span class="code" @click="send">{{time === 0 ? '发送验证码' : `${time}s后发送`}}</span>
          </div>
          <div class="error" v-if="codeError">
              <i class="iconfont icon-warning" />{{ codeError }}
            </div>
        </div>
      </template>

      <div class="form-item">
        <div class="agree">
          <XtxCheckbox v-model="isAgree" />
          <span>我已同意</span>
          <a href="javascript:;">《隐私条款》</a>
          <span>和</span>
          <a href="javascript:;">《服务条款》</a>
        </div>
        <div class="error" v-if="isAgreeError">
            <i class="iconfont icon-warning" />{{ isAgreeError }}
          </div>
      </div>
      <a href="javascript:;" class="btn" @click="login">登录</a>
      <a href="https://graph.qq.com/oauth2.0/authorize?client_id=100556005&response_type=token&scope=all&redirect_uri=http%3A%2F%2Fwww.corho.com%3A8080%2F%23%2Flogin%2Fcallback">
        <img src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png" alt="QQ登录" border="0">
      </a>
    </div>

  </div>
</template>
<script lang="ts" setup name="LoginForm">
import Message from '@/components/XtxMessage'
import { ref } from 'vue'
import useStore from '@/store'
import { useRouter } from 'vue-router'
import { useField, useForm } from 'vee-validate'
import { useCountDown } from '@/utils/hooks'
import { mobileRule, passwordRule, isAgreeRule, accountRule, codeRule } from '@/utils/validate'
// const form = ref({
//   account: '13012345683',
//   password: '123456',
//   isAgree: true
// })
const router = useRouter()
const { user } = useStore()
const { time, start } = useCountDown(5)
const type = ref<'account' | 'mobile'>('mobile')
const login = async () => {
  const res = await validate()

  if (type.value === 'account') {
    // 账号登录, 如果账号或密码或同意许可, 任何一个, 有校验错误, 就return
    if (res.errors.account || res.errors.password || res.errors.isAgree) return
    await user.login(account.value, password.value)
  } else {
    // 手机号验证码登录
    if (res.errors.mobile || res.errors.code || res.errors.isAgree) return
    await user.mobileLogin(mobile.value, code.value)
  }

  try {
    await user.login(account.value, password.value)
    // 登录成功后，合并购物车
    const { cart } = useStore()
    cart.mergeLocalCart()

    Message({ type: 'success', text: '登录成功' })
    // 跳转到首页
    router.push('/')
  } catch (err) {
    console.log(err)
    Message.error('用户名或者密码错误')
  }
}

// 表单校验
const { validate } = useForm({
  initialValues: {
    mobile: '13012345678',
    code: '123456',
    account: 'cdshi0010',
    password: '123456',
    isAgree: true
  },
  // 提供校验规则
  validationSchema: {
    mobile: mobileRule,
    code: codeRule,
    account: accountRule,
    password: passwordRule,
    isAgree: isAgreeRule
  }
})

const { value: account, errorMessage: accountError } =
  useField<string>('account')
const { value: password, errorMessage: passwordError } =
  useField<string>('password')
const { value: isAgree, errorMessage: isAgreeError } =
  useField<boolean>('isAgree')

const { value: mobile, errorMessage: mobileError, validate: validMobile } =
  useField<string>('mobile')
mobile.value = '13012345687'
const { value: code, errorMessage: codeError } =
  useField<string>('code')

const mobileRef = ref(null)
const send = async () => {
  if (time.value > 0) return
  // console.log('获取验证码')
  // 单独校验手机号
  const res = await validMobile()
  if (!res.valid) {
    // 如果没通过，自动获取手机号的焦点
    mobileRef.value!.focus()
    return
  }

  await user.sendMobileMsg(mobile.value)

  Message.success('获取验证码')
  start()
}

</script>

<style lang="less" scoped>
// 账号容器
.account-box {
  .toggle {
    padding: 15px 40px;
    text-align: right;
    a {
      color: @xtxColor;
      i {
        font-size: 14px;
      }
    }
  }
  .form {
    padding: 0 20px 20px 20px;
    &-item {
      margin-bottom: 28px;
      .input {
        position: relative;
        height: 36px;
        > i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }
        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;
          &.error {
            border-color: @priceColor;
          }
          &.active,
          &:focus {
            border-color: @xtxColor;
          }
        }
        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
        }
      }
      > .error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: @priceColor;
        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }
    .agree {
      a {
        color: #069;
      }
    }
    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: @xtxColor;
      &.disabled {
        background: #cfcdcd;
      }
    }
  }
  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}
</style>
